package com.uwo.commons.configuration.aop.validate.validate;

import com.uwo.commons.configuration.aop.validate.ValidateField;
import com.uwo.commons.configuration.aop.validate.ValidateProperties;
import com.uwo.commons.kits.MatcherKits;
import com.uwo.commons.configuration.aop.validate.ErrorCode;
import com.uwo.commons.configuration.aop.validate.annotation.Pattern;
import com.uwo.commons.configuration.aop.validate.excepteion.ApiValidateExceptrion;
import com.uwo.commons.kits.StringKits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * 格式验证
 * @author hao.yan
 */
@Component(value = "Validate_Pattern")
public class PatternValidate extends NotNullValidate{

    @Autowired
    private ValidateProperties validateProperties;

    @Override
    public void validate(Annotation annotation, ValidateField validateField) throws ApiValidateExceptrion {
        super.validate(annotation, validateField);

        if (validateField.getValue() instanceof String) {
            Pattern pattern = (Pattern)annotation;
            // 获取正则
            String p = value(validateProperties.getMessages(), pattern.pattern(), null);
            if(StringKits.isEmpty(p))
                return;
            // 编译正则表达式
            if ( !MatcherKits.matches(p, String.valueOf(validateField.getValue())) ) {
                // 属性配置
                String message = value(validateProperties.getMessages(), pattern.message(),
                        ErrorCode.FORMAT_ERROR.getMessage(validateField.getName()));
                exception(pattern.code(), message, ErrorCode.FORMAT_ERROR);
            }
        }
    }

}
